package com.yuqing.myblogServe.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.yuqing.myblogServe.common.lang.Const;
import com.yuqing.myblogServe.common.lang.Result;
import com.yuqing.myblogServe.dao.entity.SysUser;
import com.yuqing.myblogServe.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api")
@Api(value = "验证码 controller" ,tags = {"验证码接口"})
public class AuthController extends BaseController {
    @Autowired
    private Producer producer;
    @Autowired
    SysUserService sysUserService;
    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    @ApiOperation(value = "获取图片验证码")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = producer.createText();
        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        // 存储到redis中
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        return Result.succ(
                MapUtil.builder()
                        .put("token", key)
                        .put("base64Img", base64Img)
                        .build()
        );
    }
    /**
     * 获取用户信息接口
     * @param principal
     * @return
     */
    @GetMapping("/auth/userInfo")
    @ApiOperation(value = "获取当前用户信息")
    public Result userInfo(Principal principal) {

        SysUser sysUser = sysUserService.getByUsername(principal.getName());

//        return Result.succ(MapUtil.builder()
//                .put("id", sysUser.getId())
//                .put("username", sysUser.getUsername())
//                .put("avatar", sysUser.getAvatar())
//                .put("created", sysUser.getCreated())
//                .map()
//        );
        return Result.succ(sysUser);
    }
}
